import {
    getVideoList, addVideo, getTypeList, sortType, deleteVideo, moveToOther, loginUser, classList, top,
    cancelTop, addInformation, videoTemplateList, videoInfo, getVideoInfo, getThemeinformation, getFcfind, fcinfoPush, changeState,
    deleteInformation, updateVideo,getVersion,
} from '../services/fetch'
import { routerRedux } from 'dva/router';
import {
    message, notification
} from 'antd';
import { getPlateTemplate } from '../services/information';

export default {

    namespace: 'video',

    state: {
        isShowModal: false,
        submitting: false,
        initTableName: '',
        treeList: [],
        videoList: {
            pagination: {
                total: 0,
                page: 1,
                pageSize: 10,
            }
        }, //资讯列表
        dataSource: {},
        index: 1,
        selectedRowKeys: [],
        selectedPlateIds: [],//已选中的稿件id集合
        selectedPlateDatas: [],//已选中稿件data集合
        loginModal: {},   //权限
        selectedKeys: [],//已选中的树节点
        classList: [],
        dataAugment: {}, //查询数据
        videoTemplateList: [],
        informationInfo: '',
        videoInfo: '',
        themeinformation: '',
        fcfindTreeList: [],      //服务版面分类
        loading: false, //列表加载状态,
        plateSelectProps: 0,//当前选中版面管理props
        expandedKeys: [], //展开节点
        plateTemplate: {
            template_conf: {
                style: ''
            }
        }, //当前选中版面的模板类型
        total: '',
        versionJson:{list:[]},
    },

    subscriptions: {
        setup({ dispatch, history }) {  // eslint-disable-line
        },
    },

    effects: {
        /*
        *编辑资讯版面，2019-09-04 戴文锋
        */
        *editInformationPlates({ data }, { call }) {
            const res = yield call(updateVideo, data);
            if (res.data.code == 200) {
                message.success("修改成功");
                return true;
            } else {
                message.error(res.data.msg);
                return false;
            }
        },
       /**
   *获取版本配置
   */
      *getVersion({ data }, { call, put, }) {
        const res = yield call(getVersion);
        if (res.data.code == 200) {
          yield put({
            type: 'setVersion',
            payload: res.data.data
          })
          return true
        } else {
          message.error(res.msg);
          return false
        }
      },
        *getTreeList({ payload, callback }, { call, put, select }) {
            const list = yield call(getTypeList);
            const data = []
            list && list.data && list.data.data && list.data.data.map((item, index) => {
                let disabled = false;
                if (item.children) {
                    disabled = true;
                }
                if (item.is_other || item.url) {
                    disabled = true;
                }
                let obj = {
                    key: String(item.plate_id),
                    plate_id: item.plate_id,
                    title: item.plate_name,
                    children: item.children ? item.children : '',
                    value: item.plate_id,
                    disabled: disabled,
                    template_id: item.template_id,
                    template_style: item.template_style?item.template_style:'',
                    is_other: item.is_other,
                    url: item.url,
                }
                if (item.children) {
                    item.children.map((i, ins) => {
                        let obj2 = {
                            key: String(i.plate_id),
                            plate_id: i.plate_id,
                            title: i.plate_name,
                            value: i.plate_id,
                            template_id: i.template_id,
                            template_style: item.template_style?item.template_style:'',
                            is_other: i.is_other,
                        }
                        item.children[ins] = obj2
                    })
                }
                data[index] = obj
            })

            let initPlateId = 0;
            let selectedKeys = [];
            for (const item of data) {
                if (item.is_other == 0) {  //是否为其他组件  1：其他， 0非其他
                    if (item.children) {   //是否为父分类
                        initPlateId = item.children[0].plate_id;
                        selectedKeys.push(item.children[0].key);
                    } else {
                        initPlateId = item.plate_id;
                        selectedKeys.push(item.key)
                    }
                    break;
                }
            }
            yield put({ type: 'updateTreeList', data: data });
            yield put({ type: 'expandedKeys', data: selectedKeys }); //默认只展开选中的父类

            yield put({ type: 'updatePutTableName', payload: { initTableName: initPlateId, selectedKeys } });
            if (callback) callback(list.data.data, initPlateId);
        },
        *getTableList({ payload }, { call, put, select }) { //获取当前版面下资讯列表
            yield put({ type: 'setLoading', loading: true })

            const list = yield call(getVideoList, payload.dataAugment);
            yield put({ type: 'dataAugment', payload: payload.dataAugment })
            yield put({ type: 'updateTableList', data: list.data.data });
            yield put({ type: 'setLoading', loading: false })
        },
        *deleteTableList({ payload }, { call, put, select }) {
            yield call(deleteVideo, payload.dataAugment);
            message.success('删除成功');

            yield put({ type: 'getTableList', payload: { dataAugment: payload.dataSource } });
            yield put({ type: 'updateMoreDeal', data: [] });
        },
        //全局删除资讯
        *deleteInformation({ payload }, { call, put, select }) {
            yield call(deleteInformation, payload.dataAugment);
            message.success('删除成功');
            yield put({ type: 'getVideoList', data: { index: 1 } });
        },
        *backTreeList({ payload }, { call, put, select }) {
            let res = yield call(sortType, payload.dataAugment);
            if (res.data.code == 200){
                yield put({ type: 'updateTreeList', data: payload.dataAugment });
            }else{
                message.error(res.data.msg);
            }

        },
        *addVideo({ data, callback }, { call, put, select }) {
            let a = yield call(addVideo, data);
            const initTableName = yield select(state => state.video.initTableName);
            const list = yield call(getVideoList, { index: 1, plate_id: initTableName });
            yield put({ type: 'updateTableList', data: list.data.data });
            //yield put({ type: 'updateTableList', data: list });
        },
        *moveTableList({ payload }, { call, put, select }) {
            const res = yield call(moveToOther, payload.dataAugment);
            yield put({ type: 'updateMoreDeal', data: [] });
            if (res.code === 200) {
                yield put({ type: 'updateTreeList', data: payload.dataSource });
            }
        },
        *getQuanxian({ payload }, { call, put, select }) {
            let str = yield call(loginUser, payload.data);
            let arr = []
            if (str.data.code === 200) {
                arr = str.data.data.privilege_list
                yield put({ type: 'updateQuanxian', data: str.data.data });
            } else if (str.data.code === 500) {
                message.error(str.data.msg);
                yield put(routerRedux.push('/note'));
            }
        },
        /**
         * 获取分类列表
         */
        *classList({ payload }, { call, put }) {
            let list = yield call(classList);
            if (list.data) {
                if (list.data.code === 200) {
                    yield put({ type: 'saveClassList', data: list.data.data })
                }
            }
        },
        /**
         * 获取资讯列表
         */
        *getVideoList({ data }, { call, put, select }) {
            let list = yield call(getVideoList, data);
            let videoList = yield select(state => state.video.videoList);
            videoList.list = list.data.data.list;
            videoList.pagination.total = list.data.data.total;
            videoList.pagination.page = data.index;

            if (list.data.code == 200) {
                yield put({ type: 'setVideoList', data: videoList })
            } else {
                message.error(list.msg)
            }
        },
        /**
         * 资讯置顶
         */
        *top({ data }, { call, put, select }) {
            let list = yield call(top, data);
            if (list.data.code === 200) {
                message.success('置顶成功')
                const initTableName = yield select(state => state.video.initTableName);
                const list = yield call(getVideoList, { index: 1, plate_id: initTableName });
                yield put({ type: 'updateTableList', data: list.data.data });
            } else {
                message.error(list.data.msg)
            }
        },
        /**
         * 资讯取消置顶
         */
        *cancelTop({ data }, { call, put, select }) {
            let list = yield call(cancelTop, data);
            if (list.data.code === 200) {
                message.success('取消成功')
                const initTableName = yield select(state => state.video.initTableName);
                const list = yield call(getVideoList, { index: 1, plate_id: initTableName });

                yield put({ type: 'updateTableList', data: list.data.data });
                return true;
            } else {
                message.error(list.data.msg)
            }
        },
        /**
         * 复制
         */
        *copy({ data }, { call, put, select }) {
            const res = yield call(addInformation, data);
            if (res.data.code === 200) {
                message.success('复制成功');
                const list = yield call(getVideoList, { index: 1, plate_id: data.plate_id });
                yield put({ type: 'dataAugment', payload: { plate_id: data.plate_id, index: 1 } })
                yield put({ type: 'updateTableList', data: list.data.data });

            } else {
                message.error(res.data.msg)
            }
        },
        /**
         * 获取视视频模板列表
         */
        *videoTemplateList({ payload }, { call, put }) {
            let list = yield call(videoTemplateList);
            if (list.data.code === 200) {
                const data = []
                list && list.data && list.data.data && list.data.data.map((item, index) => {
                    let obj = {
                        key: String(index),
                        plate_id: item.plate_id,
                        title: item.plate_name,
                        children: item.children ? item.children : '',
                        value: item.plate_id,
                        disabled: item.children ? true : false
                    }
                    if (item.children) {
                        item.children.map((i, ins) => {
                            let obj2 = {
                                key: String(index) + '-' + ins,
                                plate_id: i.plate_id,
                                title: i.plate_name,
                                value: i.plate_id,
                            }
                            item.children[ins] = obj2
                        })
                    }
                    data[index] = obj
                })
                yield put({ type: 'saveVideoTemplateList', data: data })
            }
        },
        /**
         * 获取资讯详情
         */
        *getInformationInfo({ data, callback }, { call, put, select }) {
            const res = yield call(videoInfo, data);
            if (res.data.code === 200) {
                yield put({ type: 'updateInformationInfo', data: res.data.data });
            } else {
                yield put({ type: 'updateInformationInfo', data: {} });
                message.error(res.data.msg);
            }
            if (callback) callback();
        },
        /**
         * 获取视频详情
         */
        *getVideoInfo({ data }, { call, put, select }) {
            const res = yield call(getVideoInfo, data);
            if (res.data.code === 200) {
                yield put({ type: 'updateVideoInfo', data: res.data.data });
            } else {
                message.error('获取资讯详情失败')
            }
        },
        /**
         * 获取专题资讯详情
         */
        *getThemeinformation({ data }, { call, put, select }) {
            // const res = yield call(getThemeinformation, data);
            // if (res.data.code === 200) {
            //     yield put({ type: 'updateThemeinformation', data: res.data.data });
            // }else{
            //     message.error('获取资讯详情失败')
            // }
        },
        /**
         * 获取服务版面
         */
        *getFcfind({ callback }, { call, put, select }) {
            const list = yield call(getFcfind);
            if (list.data.code === 200) {
                const data = []
                list && list.data && list.data.data && list.data.data.map((item, index) => {
                    let obj = {
                        key: String(index),
                        plate_id: item.plate_id,
                        title: item.plate_name,
                        value: item.plate_id,
                    }
                    data[index] = obj
                })
                yield put({ type: 'updateFcfind', data: data });
                if (callback) callback(data)
            }
        },
        /**
         * 资讯推送
         */
        *fcinfoPush({ data }, { call, put, select }) {
            const list = yield call(fcinfoPush, data);
            if (list.data.code === 200) {
                message.success('推送成功')
                yield put({ type: 'updateMoreDeal', data: [] })
            } else {
                let arr = list.data.data
                if (arr.length > 0) {
                    notification.open({
                        message: '推送失败通知',
                        description: <p><b>{arr.join()}</b>推送失败，请重新推送</p>
                    });
                } else {
                    message.error(list.data.msg)
                }
            }
        },

        //更新选中左侧版面时，先获取版面样式
        *updatePutTableName({ payload }, { call, put, select }) {
            const res = yield call(getPlateTemplate, { plate_id: payload.initTableName });
            if (res.data.code == 200) {
                yield put({
                    type: 'setModelState',
                    payload: {
                        plateTemplate: res.data.data[0]
                    }
                })
            }
            yield put({
                type: 'updateTableName',
                payload: {
                    initTableName: payload.initTableName,
                    selectedKeys: payload.selectedKeys
                }
            })
        }

    },

    reducers: {
        setLoading(state, action) {
            return { ...state, loading: action.loading };
        },
        updateFcfind(state, action) {
            return { ...state, fcfindTreeList: action.data };
        },
        updateThemeinformation(state, action) {
            return { ...state, themeinformation: action.data };
        },
        updateVideoInfo(state, action) {
            return { ...state, videoInfo: action.data };
        },
        updateInformationInfo(state, action) {
            return { ...state, informationInfo: action.data };
        },
        saveVideoTemplateList(state, action) {
            return { ...state, videoTemplateList: action.data };
        },
        dataAugment(state, action) {
            return { ...state, dataAugment: action.payload };
        },
        saveClassList(state, action) {
            return { ...state, classList: action.data };
        },
        setSelectedPlateIds(state, action) {
            return { ...state, selectedPlateIds: action.data.ids, selectedPlateDatas: action.data.list };
        },
        showModal(state, action) {
            return { ...state, isShowModal: true };
        },
        hideModal(state, action) {
            return { ...state, isShowModal: false };
        },
        updateTableName(state, action) {
            return { ...state, initTableName: action.payload.initTableName, selectedKeys: action.payload.selectedKeys };
        },
        updateSelectProps(state, action) {
            return { ...state, plateSelectProps: action.data };
        },
        updateTreeList(state, action) {
            return { ...state, treeList: JSON.parse(JSON.stringify(action.data)) };
        },
        updateTableList(state, action) {
            return { ...state, dataSource: action.data };
        },
        updateMoreDeal(state, action) {
            return { ...state, selectedRowKeys: action.data };
        },
        updateIndex(state, action) {
            return { ...state, index: action.data };
        },
        updateQuanxian(state, action) {
            return { ...state, loginModal: action.data };
        },
        expandedKeys(state, action) {
            return { ...state, expandedKeys: action.data }
        },
        setModelState(state, action) {
            return { ...state, ...action.payload }
        },
        setVideoList(state, data) {
            return { ...state, videoList: data.data }
        },
        setVersion(state, { payload }) {
            return { ...state, versionJson: payload }
          },
    },

};
